﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;

public class SCAudioPlay : IStreamCapture
{

    private IntPtr audioPlay;
    private GCHandle handle;
    private Action<IntPtr, int> audioCb;
    private Action<AudioPlayParams> openAudioPlay;
    private int openIndex = 0;
    public SCAudioPlay()
    {
        if (SCInstance.Instance == null)
            new GameObject("SCInstance").AddComponent<SCInstance>().Init();
        handle = GCHandle.Alloc(this);
        audioPlay = CreateAudioPlay(GCHandle.ToIntPtr(handle));
    }

    public void OpenAsync(AudioStream _as, Action<AudioPlayParams> openCb, Action<IntPtr, int> audioCb)
    {
        if (audioPlay == IntPtr.Zero) return;
        OpenAudioPlayAsync(audioPlay, ++openIndex, _as, openAudioPlayPtr, audioPlayPtr);
        this.openAudioPlay = openCb;
        this.audioCb = audioCb;
    }

    public void Start()
    {
        if (audioPlay == IntPtr.Zero) return;
        StartAudioPlay(audioPlay);
    }

    protected override void AudioPlayCallback(IntPtr stream, int len)
    {
        if (audioCb == null) return;
        audioCb(stream, len);
    }

    protected override void OpenAudioPlayCallback(int openIndex, AudioPlayParams app)
    {
        if (openAudioPlay == null || this.openIndex != openIndex) return;
        openAudioPlay(app);
    }

    public void Memset(IntPtr mem, byte value, int len)
    {
        MemorySet(mem, value, len);
    }

    public new void MixAudioFormat(IntPtr stream, byte[] buffer, int len, float volume)
    {
        IStreamCapture.MixAudioFormat(stream, buffer, len, volume);
    }
    public void Close()
    {
        if (audioPlay == IntPtr.Zero) return;
        CloseAudioPlay(audioPlay);

    }
    public void Release()
    {
        if (audioPlay == IntPtr.Zero) return;
        DeleteAudioPlay(audioPlay);
        audioPlay = IntPtr.Zero;
    }
    ~SCAudioPlay()
    {
        Release();
    }
}
